package org.sjs.dreamfly.data

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import org.sjs.dreamfly.common.util.LogUtil
import org.sjs.dreamfly.model.MovieInfo
import org.sjs.dreamfly.model.VideoInfo

@Dao
interface VideoInfoDao {
    @Query("SELECT * FROM video_info WHERE movieId = :movieId ORDER BY title ASC")
    suspend fun query(movieId: String): List<VideoInfo>

    @Query("SELECT * FROM video_info WHERE videoId = :videoId AND movieId = :movieId")
    suspend fun query(videoId: String, movieId: String): List<VideoInfo>
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(videoInfo: VideoInfo)

    suspend fun updateOrInsert(videoInfo: VideoInfo) {
        query(videoId = videoInfo.videoId, movieId = videoInfo.movieId?:"").firstOrNull().let {
            if (it != null) {
                LogUtil.d("id:${it.id} ${it.title} is existed")
                videoInfo.id = it.id
            }
            insert(videoInfo)
        }
    }

    suspend fun sortedQuery(movieId: String): List<VideoInfo> {
        return query(movieId).sortedBy { it.title?.toLong() }
    }
}
